package com.jike.jkgame;

import java.io.IOException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jike.jkgame.MissionListAdapter.OnDoMissionListener;
import com.jike.jkgame.data.City;
import com.jike.jkgame.data.Event;
import com.jike.jkgame.data.Mission;
import com.jike.jkgame.data.MissionManager;
import com.jike.jkgame.data.MissionManager.DoMissionResult;
import com.jike.jkgame.data.MissionReward;
import com.jike.jkgame.data.UserStatus;
import com.jike.jkgame.exception.EncodingException;
import com.jike.jkgame.exception.NetworkErrorException;
import com.jike.jkgame.network.MessageFactory;
import com.jike.jkgame.network.NetworkUtilis;
import com.jike.jkgame.network.ServerConfig;

public class MissionFragment extends Fragment implements OnDoMissionListener,
		OnClickListener {

	private static final String TAG = MissionFragment.class.getSimpleName();

	private ListView mMissionLv;

	private ListView mEventLv;
	private TextView mCityTv;

	private MissionListAdapter mMissionAdapter;

	private GetAvailableMissionAsyncTask mGetAvailableMissionTask;

	private List<Event> mEventList;

	private LayoutInflater mInflater;

	private ProgressBar mConectingPb;
	private AnimationDialog mAnimDialog;
	private View mUserStatusView;

	private BaseAdapter mEventsAdaper = new BaseAdapter() {

		@Override
		public void notifyDataSetChanged() {
			mEventList = MissionManager.get().getEvents();
			super.notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView v = (TextView) convertView;
			if (v == null) {
				v = (TextView) mInflater.inflate(
						R.layout.mission2level_item_layout, null, false);
			}
			v.setText(mEventList.get(position).name);
			v.setBackgroundColor(MissionManager.get().getCurrentEventIndex() == position ? Color
					.parseColor("#448899") : Color.parseColor("#999999"));
			return v;
		}

		@Override
		public boolean isEnabled(int position) {

			return mEventList.get(position).enabled;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			if (mEventList == null) {
				return 0;
			}
			return mEventList.size();
		}
	};

	private OnItemClickListener mEventClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			GetMissionTask task = new GetMissionTask();
			MissionManager m = MissionManager.get();
			m.setCurrentEvent(mEventList.get(position).id);
			task.execute(mEventList.get(position).id);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mInflater = LayoutInflater.from(getActivity());

		mMissionAdapter = new MissionListAdapter();
		mMissionAdapter.setOnDoMissionListener(this);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.mission_layout, container, false);
		mMissionLv = (ListView) v.findViewById(R.id.lv_missions);
		mMissionLv.setAdapter(mMissionAdapter);

		mConectingPb = (ProgressBar) v.findViewById(R.id.pb_conecting);
		mCityTv = (TextView) v.findViewById(R.id.tv_city_name);

		v.findViewById(R.id.iv_city_btn).setOnClickListener(this);
		mUserStatusView = v.findViewById(R.id.user_status);

		mEventLv = (ListView) v.findViewById(R.id.lv_events);
		mEventLv.setAdapter(mEventsAdaper);
		mEventLv.setOnItemClickListener(mEventClickListener);

		mGetAvailableMissionTask = new GetAvailableMissionAsyncTask();
		mGetAvailableMissionTask.execute(0l);
		mAnimDialog = new AnimationDialog();
		return v;
	}

	@Override
	public void onResume() {
		super.onResume();
		UserStatusViewManager.get().bindView(mUserStatusView);
	}

	private void updateCityName() {
		City city = MissionManager.get().getCurrentCity();
		if (city != null) {
			mCityTv.setText(city.name);
		}
	}

	private void handleCurrentMissionResponse(String reponse) {

		if (reponse == null) {
			return;
		}

		JSONObject json;
		try {
			json = new JSONObject(reponse);

			MissionManager missionManager = MissionManager.get();

			City firstLevel = new City();
			firstLevel.id = json.getInt("first");

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	class GetAvailableMissionAsyncTask extends
			AsyncTask<Long, Integer, Boolean> {

		private int[] parseIntArrays(JSONArray json) throws JSONException {
			int[] ids = new int[json.length()];
			for (int i = 0; i < json.length(); ++i) {
				ids[i] = json.getInt(i);
			}
			return ids;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mConectingPb.setVisibility(View.GONE);
			super.onPostExecute(result);
			mEventList = MissionManager.get().getEvents();
			mMissionAdapter.notifyDataSetChanged();
			mEventsAdaper.notifyDataSetChanged();

			updateCityName();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mConectingPb.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Long... params) {
			if (params == null || params.length == 0) {
				return null;
			}

			JSONObject reqMsg = MessageFactory
					.createGetCurrentMissionReqMessage();

			// MissionManager manager = MissionManager.get();
			// manager.setCurrentMission1Level(2);
			// manager.setEnabledMission2Level(new int[]{13});
			// manager.setCurrentMission2Level(13);

			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), reqMsg);
				if (response != null) {
					JSONObject json = new JSONObject(response);

					int opcode = json.optInt("opcode");
					if (opcode != 0) {
						// 非法请求
						return Boolean.valueOf(false);
					}

					MissionManager manager = MissionManager.get();
					manager.setCurrentCity(json.getInt("1st"));
					JSONArray m2lIds = json.getJSONArray("2nds");
					int[] ids = parseIntArrays(m2lIds);
					manager.setEnabledEvents(ids);
					manager.updateMissions(json.optInt("2nd"),
							json.optJSONArray("missions"));
					return Boolean.valueOf(true);
				}

			} catch (NetworkErrorException e) {
				Log.d(TAG, e.getMessage());
			} catch (EncodingException e) {
				Log.d(TAG, e.getMessage());
			} catch (IOException e) {
				Log.d(TAG, e.getMessage());
			} catch (JSONException e) {
				Log.d(TAG, e.getMessage());
			}

			return Boolean.valueOf(false);
		}

	}

	class GetMissionTask extends AsyncTask<Integer, Integer, Integer> {

		@Override
		protected Integer doInBackground(Integer... params) {
			if (params == null || params.length == 0) {
				return null;
			}

			int parentId = params[0];
			int firstEnable = 0;

			JSONObject reqMsg = MessageFactory
					.createGetMissionListReqMessage(parentId);

			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), reqMsg);
				if (response != null) {
					JSONObject json = new JSONObject(response);
					int opcode = json.optInt("opcode", -1);

					if (opcode != 0) {
						return firstEnable;
					}

					JSONArray missions = json.optJSONArray("missions");
					firstEnable = MissionManager.get().updateMissions(parentId,
							missions);
				}

			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return firstEnable;
		}

		@Override
		protected void onPostExecute(Integer result) {
			mConectingPb.setVisibility(View.GONE);
			super.onPostExecute(result);
			mMissionAdapter.notifyDataSetChanged();
			mEventsAdaper.notifyDataSetChanged();

			if (result == MissionManager.get().getMissions().size() - 1) {
				mMissionLv.setSelection(result);
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mConectingPb.setVisibility(View.VISIBLE);
		}

	}

	class DoMissionTask extends AsyncTask<Integer, Integer, MissionReward> {
		int missionId = 0;

		@Override
		protected MissionReward doInBackground(Integer... params) {
			if (params == null || params.length == 0) {
				return null;
			}
			long start = System.currentTimeMillis();
			missionId = params[0];

			JSONObject reqMsg = MessageFactory
					.createDoMissionReqMessage(missionId);
			MissionReward reward = null;
			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), reqMsg);
				if (response != null) {
					reward = new MissionReward();
					JSONObject json = new JSONObject(response);
					int opcode = json.optInt("opcode", -1);
					reward.opcode = opcode;
					if (opcode == 0) {

						reward.energy = json.optInt("energy");
						reward.finish = json.optInt("finish");
						reward.experience = json.optInt("exp");
						reward.money = json.optInt("money");
						reward.items = NetworkUtilis.getIntArray(json
								.optJSONArray("items"));

					}
				}

			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			long remain = 2000 + start - System.currentTimeMillis();
			if (remain > 0) {
				try {
					Thread.sleep(remain);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			return reward;
		}

		@Override
		protected void onPostExecute(MissionReward result) {
			// mConectingPb.setVisibility(View.GONE);
			super.onPostExecute(result);

			if (result == null) {
				JKApp.get().showToast(R.string.network_error);
				return;
			}

			if (result.opcode == 0) {

				DoMissionResult doresult = MissionManager.get().finishMission(
						missionId, result.finish);

				UserStatus user = UserStatus.get();
				user.useEnergy(result.energy);
				user.addExpierence(result.experience);
				user.addMoney(result.money);

				if (result.items != null) {
					RewardsFrameDialog dialog = RewardsFrameDialog
							.newInstance(result);
					dialog.show(getActivity().getSupportFragmentManager(),
							"rewards");

				} else {
					Toast toast = Toast.makeText(getActivity(),
							result.getFromatedString(), Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}

				if (doresult.next) {
					GetNextMissionTask task = new GetNextMissionTask();
					task.execute(0);
				} else {
					GetMissionTask task = new GetMissionTask();
					task.execute(MissionManager.get()
							.getCurrentMission2LevelId());
				}
				mMissionAdapter.notifyDataSetChanged();
			} else if (result.opcode == 403) {
				// 精力值不足
				String name = UserStatus.get().getEnergy().name;
				ShortageAlertFragmentDialog dialog = ShortageAlertFragmentDialog
						.newInstance(UserStatus.get().getEnergy().name);
				dialog.show(getActivity().getSupportFragmentManager(), name);
			} else if (result.opcode == 405) {
				Toast.makeText(getActivity(), "此任务不可做！", Toast.LENGTH_SHORT)
						.show();
			}

			((MainActivity) getActivity())
					.updateUserStatus(UserStatusFragment.ENERGY
							| UserStatusFragment.EXPERIENCE
							| UserStatusFragment.MONEY);
			mAnimDialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// mConectingPb.setVisibility(View.VISIBLE);
			mAnimDialog.show(getActivity().getSupportFragmentManager(), "anim");
		}

	}

	class GetNextMissionTask extends AsyncTask<Integer, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {
			// if(params == null) {
			// return Boolean.valueOf(false);
			// }
			MissionManager manager = MissionManager.get();
			JSONObject reqMsg = MessageFactory
					.createGetEventListReqMessage(manager.getCurrentCityId());
			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), reqMsg);
				if (response != null) {
					JSONObject json = new JSONObject(response);
					int[] ids = NetworkUtilis.getIntArray(json
							.optJSONArray("2nds"));
					manager.setEnabledEvents(ids);

					reqMsg = MessageFactory
							.createGetMissionListReqMessage(manager
									.getCurrentMission2LevelId());
					response = NetworkUtilis.getHttpString(ServerConfig.get()
							.getGameServer(), reqMsg);
					json = new JSONObject(response);

					manager.updateMissions(manager.getCurrentMission2LevelId(),
							json.optJSONArray("missions"));

					return Boolean.valueOf(true);
				}

			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return Boolean.valueOf(false);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mConectingPb.setVisibility(View.GONE);
			super.onPostExecute(result);
			mEventsAdaper.notifyDataSetChanged();
			mMissionAdapter.notifyDataSetChanged();

			updateCityName();
			mMissionLv.setSelection(0);
		}

		@Override
		protected void onPreExecute() {
			mConectingPb.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

	}

	private void showDialog() {
		String name = UserStatus.get().getEnergy().name;
		ShortageAlertFragmentDialog dialog = ShortageAlertFragmentDialog
				.newInstance(UserStatus.get().getEnergy().name);
		dialog.show(getActivity().getSupportFragmentManager(), name);

		// DialogFragment dialog = new RewardsFrameDialog();
		// dialog.show(getActivity().getSupportFragmentManager(), "rewards");
	}

	/**
	 * 检查做此任务的前提条件是否满足（精力值和等级）
	 * 
	 * @param mission
	 * @return true 表示能够执行此任务 false 条件不满足，不能执行
	 */
	private boolean checkRequirement(Mission mission) {
		UserStatus status = UserStatus.get();
		return (status.getEnergy().value >= mission.energy);
	}

	@Override
	public boolean onStartMission(int missionId) {
		// mMissionLv.setEnabled(false);

		DoMissionTask task = new DoMissionTask();
		task.execute(missionId);

		return true;

		// if (checkRequirement(mission) ) {
		//
		// return true;
		// } else {
		// return false;
		// }
	}

	@Override
	public boolean onFinishMission(int missionId, boolean succeed) {
		mMissionLv.setEnabled(true);
		// if (succeed) {
		// UserStatus.get().getEnergy().use(100);
		// }
		return true;
	}

	@Override
	public boolean onCancelMission(int missionId) {
		mMissionLv.setEnabled(true);
		showDialog();

		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_city_btn: {
			Intent intent = new Intent(getActivity(), CitiesActivity.class);
			startActivityForResult(intent, 1002);
		}
			break;
		default:
			break;
		}

	}

}
